while Loop in C++

Posted on December 9, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

while loop is like a "do this while that's true" loop. It repeats a task over and over as long as a condition remains true. It's great when you're not sure how many times you need to do something. If you already know the exact number of times, use a for loop.

Syntax of while Loop:

while (condition) {
// Code to be executed as long as the condition is true
}

1. Condition Check:

    (a.) Evaluate the boolean condition of the while loop.

    (b.) If the condition is false, exit the loop.

    (c.) If the condition is true, proceed to the next step.

2. Execute the Loop Body:

    (a.) Execute the statements or code block inside the loop.

    (b.) Perform any actions specified within the loop body.

3. Return to Condition Check:

    (a.) Go back to step 1 and re-evaluate the condition.

    (b.) If the condition is still true, repeat steps 2 and 3.

    (c.) If the condition is false, exit the loop.

This process repeats until the condition becomes false. It's essential to ensure that the condition can become false at some point to prevent an infinite loop. The loop will keep executing as long as the condition remains true.

Example of while loop:

#include <iostream>Copy Code
using namespace std;

int main() {

    int i = 1;
    while (i <= 5) {
        std::cout << i << " ";
        i++;
    }

    return 0;
}

In the above example, i is initially set to 1 the while loop checks if i is less than or equal to 5 or if the condition is true, it prints the value of i and increments i.The loop continues until i is no longer less than or equal to 5.
The output of this loop will be 1 2 3 4 5.